package com.idea.zd.sys.util;

import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成PDF文件的工具类
 * 
 * @author wjj
 * 
 */
public class PdfUtil {

	private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(PdfUtil.class);



	public boolean createPDF(Map dataMap, String templateName, String fileName){
		String htmlContent;
		BufferedWriter writer;
		try {
			//创建配置实例
			Configuration configuration = new Configuration();

			//设置编码
			configuration.setDefaultEncoding("UTF-8");

			//ftl模板文件统一放至 com.lun.template 包下面
			configuration.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir")+"/src/main/resources/template/"));

			//获取模板
			Template template = configuration.getTemplate(templateName);

			StringWriter stringWriter = new StringWriter();
			writer = new BufferedWriter(stringWriter);


			//生成文件
			template.setEncoding("UTF-8");
			template.process(dataMap, writer);
			htmlContent = stringWriter.toString();

			return createPDF(htmlContent,fileName);
		} catch (Exception e) {
			log.error("模块设置失败");
			e.printStackTrace();
			return false;
		}
	}

	private boolean createPDF(String htmlContent, String outputFile){

		try {
			OutputStream out;
			/*DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();

			Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));*/
			File f = new File(outputFile);
			if (f != null && !f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			out = new FileOutputStream(outputFile);
			ITextRenderer iTextRenderer = new ITextRenderer();
			ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
			fontResolver.addFont(System.getProperty("user.dir")+"/src/main/resources/ARIALUNI.TTF", BaseFont.IDENTITY_H,
					BaseFont.NOT_EMBEDDED);
			//
			iTextRenderer.setDocumentFromString(htmlContent);
			iTextRenderer.layout();
			iTextRenderer.createPDF(out);
			log.debug("PDF--"+outputFile+"生成成功！");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("PDF生成失败");
			return false;
		}

	}

	public static void main(String [] args)throws Exception{

		Map<String,String> map = new HashMap<>();
		map.put("name","中国万岁");


		PdfUtil pdfUtil = new PdfUtil();
		Long startTime = System.currentTimeMillis();
		pdfUtil.createPDF(map,"temp.html","E:/bbdf/sfsdfa/test.pdf");
		System.out.println((System.currentTimeMillis()-startTime)/1000/60);


		/*FileInputStream fileInputStream = new FileInputStream("F:\\sys_db\\src\\main\\resources\\template\\temp.html");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

		//字节数组
		String tempStr = "";
		String str = "";

		while((tempStr = bufferedReader.readLine())!=null){

			str+=tempStr;
		}

		bufferedReader.close();
		fileInputStream.close();


		// 字符串转XML
		String xmlStr = str;
		System.out.println(xmlStr.getBytes("UTF-8"));
		StringReader sr = new StringReader(xmlStr);
		InputSource is = new InputSource(sr);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=factory.newDocumentBuilder();
		Long startTime = System.currentTimeMillis();
		Document doc = builder.parse(is);
		System.out.println((System.currentTimeMillis()-startTime)/1000/60);*/
	}
}
